<template>
    <!-- 提交订单页面 -->
    <!-- lzy 2023年4月5日 15点19分 -->
    <div id="submit_order" v-loading="loading">
        <div class="submit_order_box">
            <div class="submit_order_header">
                <img class="logo" :src="logo" alt="">
                <p style="float:left;font-size:26px;margin-left: 16px;">结算页</p>
            </div>
            <p style="font-size: 18px;">填写并核对订单信息</p>
            <el-card>
                <h3>收货人信息</h3>
                <span @click="addAddress" class="addAddress">添加收货地址</span>
                <div class="address_list">
                    <el-radio 
                    fill="#71B247"
                    v-for="item in userAddressList" 
                    :key="item.id" 
                    v-model="ordersForm.addressRadio"
                    @input="addressInput()"
                    :label="item.id" 
                    style="margin: 0;margin-top: 10px;"
                    border>
                    {{item.addressConsignee}}
                    {{item.addressLocationProvince}} 
                    {{item.addressLocationCity}}
                    {{item.addressLocationCounty}}
                    {{item.addressDetailed}}
                    {{item.addressTelephoneShift}} 
                    </el-radio>
                </div>
                <el-divider></el-divider>
                <!-- 支付方式main -->
                <h3>支付方式</h3>
                <el-radio 
                fill="#71B247"
                v-for="item in payModeList" 
                :key="item.id" 
                v-model="payModeId" 
                :label="item.mode" 
                border>
                </el-radio>
                <el-divider></el-divider>
                <!-- 商品信息main -->
                <h4>商品信息</h4>
                <div class="commodity_box" v-for="item,index in commodityList" :key="index + 'commodity'">
                    <img class="commodity_image" :src="imageUrl + '?id=' + (item.imageId).split(',')[0]" alt="">
                    <div class="commodity_context">
                        <span>{{item.commodityName}}</span>
                        <br>
                        <span class="commodity_back">{{item.back}}</span>
                        <span class="commodity_num">x{{item.num}}</span>
                        <p class="commodity_price">￥{{item.price}}</p>
                        <p class="commodity_favorablePrice">￥{{item.favorablePrice}}</p>
                    </div>
                </div>
                <!-- 手工diy定制main -->
                <div class="diy_box" v-for="item,index in diyList" :key="index + 'diy'">
                    <img class="diy_image" :src="imageUrl + '?id=' + item.diyImageId" alt="">
                    <div class="diy_context">
                        <span>{{item.diyName}}</span>
                        <br>
                        <span class="diy_details">{{item.diyDetails}}</span>
                        <span class="diy_num">x{{item.num}}</span>
                        <div style="position: absolute;bottom:0;left:110px;">
                            <span>到店时间：</span>
                            <el-date-picker
                            v-model="item['arrivalTime']"
                            @change="changeArrivalTime(item.arrivalTime, item.id)"
                            type="date"
                            :picker-options="pickerOptions"
                            placeholder="选择日期">
                            </el-date-picker>
                            <span style="margin-left:50px;">到店人数：</span>
                            <el-input-number @change="changeArrivalNum" v-model="item.arrivalNum" :min='1' :max="item.recommendedPeopleNumber" :step="1"></el-input-number>
                        </div>
                        <p class="commodity_price">￥{{item.diyPrice}}</p>
                        <p class="commodity_favorablePrice">￥{{item.diyFavorablePrice}}</p>
                    </div>
                </div>
            </el-card>
            <div class="price_list">
                <div style="width: 300px;height:100%;float:right;">
                    <span>总商品金额：</span>
                    <span class="commodityAmountTotal">￥{{ordersForm.commodityAmountTotal}}</span>
                    <p>运费：￥{{ordersForm.freight}}</p>
                </div>
            </div>
            <div class="submit_order_footer">
                <div style="width: 300px;height:100%;float:right;">
                    <span>应付总金额：</span>
                    <span class="orderAmountTotal">￥{{ordersForm.orderAmountTotal = ordersForm.commodityAmountTotal + ordersForm.freight}}</span>
                </div>
                <div style="position: absolute;bottom:20px;right:25px">
                    <span style="color: #666666">
                        寄送至：
                        {{userAddress.addressConsignee}}
                        {{userAddress.addressLocationProvince}} 
                        {{userAddress.addressLocationCity}}
                        {{userAddress.addressLocationCounty}}
                        {{userAddress.addressDetailed}}
                        {{userAddress.addressTelephoneShift}} 
                    </span>
                </div>
            </div>  
            <el-button @click="checkSubmitOrder" class="submit_btn" type="danger">提交订单</el-button>
        </div>
    </div>
</template>

<script>
// 引入logo图片
import logo from "../../../src/assets/image/logo.png"
// 引入底部组件
import Bottom from '../../components/home/Bottom.vue'
export default {
    data () {
        return {
            // 加载状态
            loading: false,
            pickerOptions: {
                disabledDate(time) {
                    // 限制收货时间不让选择今天以前的
                    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
                }
            },
            // 支付方式信息列表
            payModeList: [],
            // diy信息列表
            diyList: [],
            // 商品信息列表
            commodityList: [],
            // 支付方式单选框
            payModeId: '',
            // diy id数组
            diyIds: '1,2,1,1,1',
            // 商品id数组
            commodityIds: '1,2,3,4',
			// 商品id 商品数量信息列表
			commodityArr: [],
			// diy商品id diy商品数量信息列表
			diyArr: [],
            // orders表单
            ordersForm: {
                // 订单总金额
                orderAmountTotal: 0,
                // 商品总金额
                commodityAmountTotal: 0,
                // 运费
                freight: 0,
                // 支付方式单选框
                payModeId: '1',
                // 购买人
                userId: 1,
                // 收货地址
                addressRadio: '',
            },
            // 图片服务器路径
            imageUrl: '',
            logo: '',
            // 用户收货地址
            userAddressList: [],
            // 存放用户收货地址对象
            userAddress: {},
        }
    },
    components: {
        Bottom
    },
    created () {   
        this.ordersForm.userId = window.sessionStorage.getItem("userId")
    },
    mounted () {
        // 合并diyIds和commodityIds id数组
        this.diyAndCommodityIdsMerge()
        this.logo = logo
        // 图片服务器路径赋值
        this.imageUrl = this.$imageUrl
        // 初始化获取支付方式信息列表
        this.getPayModeList()
        // 根据用户id获取用户收货地址
        this.getAddressByUserId()
    },
    methods: {
        // 添加收货地址
        addAddress () {
            this.$router.push({name: "address"})
        },
        // 合并diyIds和commodityIds id数组
        diyAndCommodityIdsMerge () {
            // 判断diy商品是否为null
            if (JSON.parse(this.$Base64.decode(this.$route.query.diyArr)).length != 0) {
                // 获取diy商品id数组
                this.diyArr = JSON.parse(this.$Base64.decode(this.$route.query.diyArr))
                this.diyIds = (this.diyArr.map(v=>v.id)).join(',')
                // 初始化根据diy id获取diy商品信息
                this.getDiyListByIds()
            }
            // 判断商品是否为null
            if (JSON.parse(this.$Base64.decode(this.$route.query.commodityArr)).length != 0) {
                // 获取商品id数组
                this.commodityArr = JSON.parse(this.$Base64.decode(this.$route.query.commodityArr))
                this.commodityIds = (this.commodityArr.map(v=>v.id)).join(',')
                // 初始化根据商品 id获取商品信息列表
                this.getCommodityListByIds()
            }
        },
        // 校验提交订单
        checkSubmitOrder () {
            try{
                if(this.ordersForm.addressRadio !== '') {
                    // 校验是否选择支付方式
                    if (this.payModeId !== '') {
                        // 校验 提交的订单中是否存在diy商品订单
                        if (this.diyArr.length > 0) {
                            let flag = true
                            this.diyArr.forEach(item => {
                                // 判断是否选择到店时间
                                if (item.arrivalTime == '') {
                                    this.message('请填写到店时间', 'warning')
                                    flag = false
                                    //报错，就跳出循环
                                    throw new Error();
                                } else {
                                    flag = true
                                }
                            })
                            if (flag) {
                                this.submitDiyOrder()
                            }
                        } else {
                            this.submitOrder()
                        }
                    } else {
                        this.message('请选择支付方式', 'warning')
                    }
                } else {
                    this.message('请选择收货地址', 'warning')
                }
            }catch(e){
            }

        },
        submitOrder () {
            // 开启加载遮罩
            this.loading = true
            this.$axios.post("/seckill/submitOrder", 
                {
                    productArr: JSON.stringify(this.commodityArr),
                    orderAmountTotal: this.ordersForm.orderAmountTotal,
                    commodityAmountTotal: this.ordersForm.commodityAmountTotal,
                    freight: this.ordersForm.freight,
                    addressId: this.ordersForm.addressRadio,
                    payModeId: this.ordersForm.payModeId,
                    userId: this.ordersForm.userId,
                },
            ).then(res => {
                if (res.data.flag) {
                  this.message(res.data.data, 'warning')
                  this.pollingOrder()
                } else{
                  this.loading = false
                  this.message(res.data.data, 'warning')
                }
            })
        },
        //轮询请求查看商品订单生成状态
        pollingOrder () {
            this.$axios.post("/seckill/sendResult", {
                productArr: JSON.stringify(this.commodityArr),
                userId: this.ordersForm.userId,
            }).then(res => {
              console.log(res)
              //查看订单是否还在生成中
              if(res.data.data == 0){
                //还在订单生成中，等两秒后重新请求
                setTimeout(() =>{
                  this.pollingOrder()
                },2000)
              }else{
                const orderNumberList = res.data.data
                // 判断生成几个订单
                if (orderNumberList.length > 1) {
                    this.$router.push({
                        name: 'MyOrder'
                    })
                } else {
                    // 调用阿里云支付接口
                    this.$axios.post("/Alipay/qrcode", orderNumberList[0]).then(res => {
                        if (res.data.flag) {
                            this.loading = false
                            console.log(orderNumberList[0])
                            this.$router.push({
                                path: 'Alipay',
                                query:{
                                    // 订单编号
                                    orderNumber: this.$Base64.encode(res.data.data.orderNumber),
                                    // 订单价格
                                    price: this.$Base64.encode(res.data.data.price),
                                    // 二维码连接
                                    qrCode: this.$Base64.encode(res.data.data.QrCode),
                                    // 支付订单号
                                    outTradeNo: this.$Base64.encode(res.data.data.outTradeNo),
                                    // 订单类型
                                    orderTypeId: this.$Base64.encode(orderNumberList[0].orderTypeId)
                                }
                            })
                        }
                    })
                }
              }
            })
        },
        // 提交订单
        submitDiyOrder () {
            // 开启加载遮罩
            this.loading = true
            // const formdata = new FormData()
            // formdata.set("diyArr", JSON.stringify(this.diyArr))
            // formdata.set("commodityArr", JSON.stringify(this.commodityArr))
            // formdata.set("orderAmountTotal", this.ordersForm.orderAmountTotal)
            // formdata.set("commodityAmountTotal", this.ordersForm.commodityAmountTotal)
            // formdata.set("freight", this.ordersForm.freight)
            // formdata.set("addressId", this.ordersForm.addressRadio)
            // formdata.set("payModeId", this.ordersForm.payModeId)
            // formdata.set("userId", this.ordersForm.userId)
            this.$axios.post("/order/submitHandDiyOrder", 
                {
                    productArr: JSON.stringify(this.diyArr),
                    orderAmountTotal: this.ordersForm.orderAmountTotal,
                    commodityAmountTotal: this.ordersForm.commodityAmountTotal,
                    freight: this.ordersForm.freight,
                    addressId: this.ordersForm.addressRadio,
                    payModeId: this.ordersForm.payModeId,
                    userId: this.ordersForm.userId,
                },
            ).then(res => {
                if (res.data.flag) {
                    const orderNumberList = res.data.data
                    // 判断生成几个订单
                    if (orderNumberList.length > 1) {
                        this.$router.push({
                            name: 'MyOrder'
                        })
                    } else {
                        // 调用阿里云支付接口
                        this.$axios.post("/Alipay/qrcode", orderNumberList[0]).then(res => {
                            if (res.data.flag) {
                                this.loading = false
                                this.$router.push({
                                    path: 'Alipay',
                                    query:{
                                        // 订单编号
                                        orderNumber: this.$Base64.encode(res.data.data.orderNumber),
                                        // 订单价格
                                        price: this.$Base64.encode(res.data.data.price),
                                        // 二维码连接
                                        qrCode: this.$Base64.encode(res.data.data.QrCode),
                                        // 支付订单号
                                        outTradeNo: this.$Base64.encode(res.data.data.outTradeNo),
                                        // 订单类型
                                        orderTypeId: this.$Base64.encode(orderNumberList[0].orderTypeId)
                                    }
                                })
                            }
                        })
                    }
                } else {
                    this.loading = false
                    this.message(res.data.data, 'warning')
                }
            })
        },
        open() {
            this.$alert('这是一段内容', '标题名称', {
            confirmButtonText: '确定',
                callback: action => {
                    this.$message({
                    type: 'info',
                    message: `action: ${ action }`
                    });
                }
            });
        },
        // 选择到店人数触发方法
        changeArrivalNum () {
            
        },
        // 选择到店时间触发方法
        changeArrivalTime (arrivalTime, diyId) {
            this.diyArr.forEach(item => {
                if (item.id == diyId) {
                    item.arrivalTime = arrivalTime
                }
            })
        },
        // 选择收货地址触发方法
        addressInput () {
            this.userAddressList.forEach(item => {
                if (item.id === this.ordersForm.addressRadio) {
                    this.userAddress = item
                }
            })
        },
        // 根据用户id获取用户收货地址
        getAddressByUserId () {
            this.$axios.get("/userAddress/getAddressByUserId", {
                params: {
                    userId: this.ordersForm.userId
                }
            }).then(res => {
                if (res.data.flag & res.data.data.length > 0) {
                    this.userAddressList = res.data.data
                    this.ordersForm.addressRadio = this.userAddressList[0].id
                    // 赋值默认收货地址
                    this.userAddress = this.userAddressList[0]
                }
            })
        },
        // 获取支付方式信息列表
        getPayModeList () {
            this.$axios.get("/payMode/getPayModeList").then(res => {
                if (res.data.flag) {
                    this.payModeList = res.data.data
                }
            })
        },
        // 根据diy id获取diy商品信息
        getDiyListByIds () {
            this.$axios.get("/handworkDiy/getHandworkDiyListByIds", {
                params: {
                    ids: this.diyIds
                }
            }).then(res => {
                if (res.data.flag) {
                    this.diyList = res.data.data
					// 根据diy商品数量计算总价格
                    this.diyList.forEach(element => {
						let diyPrice = 0
						this.diyArr.forEach(item => {
							if (element.id == item.id) {
								diyPrice = (element.diyFavorablePrice * item.number)
								// 对象插入变量
								element['num'] = item.number
                                item['arrivalNum'] = 1
                                element['arrivalNum'] = 1
                                item['arrivalTime'] = ''
                                item['totalPrice'] = diyPrice 
							}
						})
						this.ordersForm.commodityAmountTotal += diyPrice
                    });
                }
            })
        },
        // 根据商品 id获取商品信息列表
        getCommodityListByIds () {
            this.$axios.get("/commodity/detail/getCommodityListByIds", {
                params: {
                    ids: this.commodityIds
                }
            }).then(res => {
                if (res.data.flag) {
                    this.commodityList = res.data.data
					// 根据商品数量计算总价格
                    this.commodityList.forEach(element => {
						let commodityPrice = 0
						this.commodityArr.forEach(item => {
							if (element.id == item.id) {
								commodityPrice = (element.favorablePrice * item.number)
								// 对象插入变量
								element['num'] = item.number
                                // 
                                item['totalPrice'] = commodityPrice
							}
						})
						this.ordersForm.commodityAmountTotal += commodityPrice
                    });
                }
            })
        },
        //信息弹窗
        message (message, type) {
			this.$message({
				message: message,
				type: type
			})
		}
    }
}
</script>

<style scoped>
#bottom{
    margin: 0 auto;
    height: 100px;
    margin-top: 100px;
}
.submit_order_header{
    overflow: hidden;
    line-height: 70px;
}
.logo{
    width: 170px;
    float:left;
}
#submit_order{
    width: 100%;
    height: 100%;
}
.submit_order_box{
    width: 1300px;
    height: 100%;
    margin: 0 auto;
    margin-top: 20px;
}
.commodity_image{
    width: 100px;
    height: 100px;
    float: left;
}
.diy_image{
    width: 100px;
    height: 100px;
    float: left;
}
.commodity_box{
    width: 100%;
    height: 110px;
    margin: 5px 0;
    position: relative;
}
.diy_box{
    width: 100%;
    height: 110px;
    margin: 5px 0;
    position: relative;
}
.commodity_context{
    float: left;
    margin-left: 10px;
}
.diy_context{
    float: left;
    margin-left: 10px;
}
.commodity_back{
    display: block;
    width: 300px;
    font-size: 12px;
    color: #666666;
    margin-top: 10px;
}
.diy_details{
    display: block;
    width: 300px;
    font-size: 12px;
    color: #666666;
    margin-top: 10px;
}
.price_list{
    width: 100%;
    height: 90px;
    padding: 15px 0;
    line-height: 32px;
}
.submit_order_footer{
    width: 100%;
    height: 70px;
    background-color: #F4F4F4;
    padding: 15px 0;
    position: relative;
}
.submit_btn{
    width: 200px;
    height: 50px;
    font-size: 16px;
    float: right;
    margin-top: 20px;
}
.commodity_favorablePrice{
    margin: 0;
    position: absolute;
    top: 38px;
    right: 0px;
    color: #E4393C;
    font-weight: bold;
}
.commodity_price{
    margin: 0;
    position: absolute;
    top: 10px;
    right: 0px;
    text-decoration:line-through;
    color: #666666;
    font-size: 10px;
}
.commodityAmountTotal{
    margin-left: 10px;
}
.orderAmountTotal{
    font-size: 24px;
    color: #E4393C;
    font-weight: bold;
    margin-left: 10px;
}
.commodity_num{
	position: absolute;
	top: 15px;
	right: 300px;
}
.diy_num{
	position: absolute;
	top: 15px;
	right: 300px;
}
.addAddress{
    cursor: pointer;
}
.address_list{
    width: 500px;
    height: 200px;
    overflow: hidden;
    overflow: scroll;
}
</style>